#include "recordsviewwidget.h"
#include "ui_recordsviewwidget.h"
#include "recorddetaildialog.h"
#include <QDebug>

RecordsViewWidget::RecordsViewWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::RecordsViewWidget)
{
    ui->setupUi(this);
    
    // 设置表格属性
    ui->recordsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->recordsTable->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->recordsTable->setAlternatingRowColors(true);
    ui->recordsTable->horizontalHeader()->setStretchLastSection(true);
    
    // 设置表格列标题
    ui->recordsTable->setColumnCount(6);
    QStringList headers;
    headers << "ID" << "时间" << "操作员" << "物品名称" << "操作类型" << "数量";
    ui->recordsTable->setHorizontalHeaderLabels(headers);
    
    // 设置列宽
    ui->recordsTable->setColumnWidth(0, 60);   // ID
    ui->recordsTable->setColumnWidth(1, 140);  // 时间
    ui->recordsTable->setColumnWidth(2, 80);   // 操作员
    ui->recordsTable->setColumnWidth(3, 180);  // 物品名称
    ui->recordsTable->setColumnWidth(4, 80);   // 操作类型
    ui->recordsTable->setColumnWidth(5, 100);  // 数量
    
    // 设置日期控件的默认值
    ui->startDateEdit->setDate(QDate::currentDate().addDays(-30)); // 默认30天前
    ui->endDateEdit->setDate(QDate::currentDate()); // 默认今天
    ui->startDateEdit->setCalendarPopup(true);
    ui->endDateEdit->setCalendarPopup(true);
    
    // 连接信号槽
    connect(ui->searchBtn, &QPushButton::clicked, this, &RecordsViewWidget::onSearchClicked);
    connect(ui->resetBtn, &QPushButton::clicked, this, &RecordsViewWidget::onResetClicked);
    connect(ui->exportBtn, &QPushButton::clicked, this, &RecordsViewWidget::onExportClicked);
    connect(ui->viewDetailBtn, &QPushButton::clicked, this, &RecordsViewWidget::onViewDetailClicked);
    connect(ui->recordsTable, &QTableWidget::cellDoubleClicked, this, &RecordsViewWidget::onTableDoubleClicked);
    connect(ui->userComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &RecordsViewWidget::onUserSelectionChanged);
    
    // 初始化时禁用需要选择的按钮
    ui->viewDetailBtn->setEnabled(false);
    ui->exportBtn->setEnabled(false);
    
    // 监听表格选择变化
    connect(ui->recordsTable, &QTableWidget::itemSelectionChanged, this, [this]() {
        bool hasSelection = ui->recordsTable->currentRow() >= 0;
        ui->viewDetailBtn->setEnabled(hasSelection);
    });
    
    // 加载下拉框数据
    loadUsers();
    loadItems();
}

RecordsViewWidget::~RecordsViewWidget()
{
    delete ui;
}

// 设置当前用户
void RecordsViewWidget::setCurrentUser(const UserInfo& userInfo)
{
    m_currentUser = userInfo;
    
    // 如果是普通用户，只显示自己的记录
    if (userInfo.role == "user") {
        ui->userComboBox->setEnabled(false);
        // 在用户下拉框中选中当前用户
        for (int i = 0; i < ui->userComboBox->count(); ++i) {
            if (ui->userComboBox->itemData(i).toInt() == userInfo.id) {
                ui->userComboBox->setCurrentIndex(i);
                break;
            }
        }
    } else {
        ui->userComboBox->setEnabled(true);
    }
}

// 刷新记录列表
void RecordsViewWidget::refreshRecords()
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    
    if (m_currentUser.role == "user") {
        // 普通用户只能看自己的记录
        m_currentRecords = dbManager.getUserRecords(m_currentUser.id);
    } else {
        // 管理员可以看所有记录
        m_currentRecords = dbManager.getStockRecords();
    }
    
    loadRecordsToTable(m_currentRecords);
    updateStatistics();
    
    ui->exportBtn->setEnabled(!m_currentRecords.isEmpty());
}

// 加载用户下拉框
void RecordsViewWidget::loadUsers()
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    m_allUsers = dbManager.getAllUsers();
    
    ui->userComboBox->clear();
    ui->userComboBox->addItem("所有用户", -1);
    
    for (const UserInfo& user : m_allUsers) {
        QString displayText = QString("%1 (%2)").arg(user.username, 
                                    user.role == "admin" ? "管理员" : "普通用户");
        ui->userComboBox->addItem(displayText, user.id);
    }
}

// 加载物品下拉框
void RecordsViewWidget::loadItems()
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    m_allItems = dbManager.getAllItems();
    
    ui->itemComboBox->clear();
    ui->itemComboBox->addItem("所有物品", -1);
    
    for (const ItemInfo& item : m_allItems) {
        QString displayText = QString("%1 (%2)").arg(item.name, item.model);
        ui->itemComboBox->addItem(displayText, item.id);
    }
}

// 加载记录到表格
void RecordsViewWidget::loadRecordsToTable(const QList<StockRecord>& records)
{
    ui->recordsTable->setRowCount(records.size());
    
    for (int i = 0; i < records.size(); ++i) {
        const StockRecord& record = records[i];
        
        // ID
        QTableWidgetItem* idItem = new QTableWidgetItem(QString::number(record.id));
        idItem->setTextAlignment(Qt::AlignCenter);
        idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable);
        ui->recordsTable->setItem(i, 0, idItem);
        
        // 时间
        QTableWidgetItem* timeItem = new QTableWidgetItem(record.timestamp);
        timeItem->setFlags(timeItem->flags() & ~Qt::ItemIsEditable);
        ui->recordsTable->setItem(i, 1, timeItem);
        
        // 操作员
        QTableWidgetItem* userItem = new QTableWidgetItem(record.username);
        userItem->setFlags(userItem->flags() & ~Qt::ItemIsEditable);
        ui->recordsTable->setItem(i, 2, userItem);
        
        // 物品名称
        QTableWidgetItem* itemItem = new QTableWidgetItem(record.itemName);
        itemItem->setFlags(itemItem->flags() & ~Qt::ItemIsEditable);
        ui->recordsTable->setItem(i, 3, itemItem);
        
        // 操作类型
        QTableWidgetItem* typeItem = new QTableWidgetItem(record.type);
        typeItem->setFlags(typeItem->flags() & ~Qt::ItemIsEditable);
        typeItem->setTextAlignment(Qt::AlignCenter);
        
        // 根据操作类型设置颜色
        if (record.type == "入库") {
            typeItem->setForeground(QBrush(QColor(40, 167, 69))); // 绿色
        } else if (record.type == "出库") {
            typeItem->setForeground(QBrush(QColor(220, 53, 69))); // 红色
        }
        ui->recordsTable->setItem(i, 4, typeItem);
        
        // 数量
        QTableWidgetItem* quantityItem = new QTableWidgetItem(QString::number(record.quantity));
        quantityItem->setTextAlignment(Qt::AlignCenter);
        quantityItem->setFlags(quantityItem->flags() & ~Qt::ItemIsEditable);
        ui->recordsTable->setItem(i, 5, quantityItem);
        
    }
}

// 获取搜索条件
RecordFilter RecordsViewWidget::getSearchFilter()
{
    RecordFilter filter;
    
    filter.startDate = ui->startDateEdit->date().toString("yyyy-MM-dd");
    filter.endDate = ui->endDateEdit->date().toString("yyyy-MM-dd");
    
    int selectedUserId = ui->userComboBox->currentData().toInt();
    if (selectedUserId > 0) {
        filter.userId = selectedUserId;
    }
    
    int selectedItemId = ui->itemComboBox->currentData().toInt();
    if (selectedItemId > 0) {
        filter.itemId = selectedItemId;
    }
    
    QString selectedType = ui->typeComboBox->currentText();
    if (selectedType != "所有类型") {
        filter.type = selectedType;
    }
    
    return filter;
}

// 更新统计信息
void RecordsViewWidget::updateStatistics()
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    QVariantMap stats = dbManager.getRecordsStatistics();
    
    ui->totalRecordsLabel->setText(QString("总记录数: %1").arg(stats["totalRecords"].toInt()));
    ui->monthlyRecordsLabel->setText(QString("本月操作: %1").arg(stats["monthlyRecords"].toInt()));
    ui->stockInLabel->setText(QString("本月入库: %1").arg(stats["monthlyStockIn"].toInt()));
    ui->stockOutLabel->setText(QString("本月出库: %1").arg(stats["monthlyStockOut"].toInt()));
    ui->todayRecordsLabel->setText(QString("今日操作: %1").arg(stats["todayRecords"].toInt()));
    ui->activeUsersLabel->setText(QString("活跃用户: %1").arg(stats["activeUsers"].toInt()));
}

// 获取选中的记录
StockRecord RecordsViewWidget::getSelectedRecord()
{
    StockRecord record;
    int currentRow = ui->recordsTable->currentRow();
    
    if (currentRow >= 0 && currentRow < m_currentRecords.size()) {
        record = m_currentRecords[currentRow];
    }
    
    return record;
}

// 检查是否有选中项
bool RecordsViewWidget::hasSelection()
{
    return ui->recordsTable->currentRow() >= 0;
}

// 搜索按钮点击
void RecordsViewWidget::onSearchClicked()
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    RecordFilter filter = getSearchFilter();
    
    // 如果是普通用户，强制设置用户ID
    if (m_currentUser.role == "user") {
        filter.userId = m_currentUser.id;
    }
    
    m_currentRecords = dbManager.getFilteredRecords(filter);
    loadRecordsToTable(m_currentRecords);
    
    ui->exportBtn->setEnabled(!m_currentRecords.isEmpty());
    
    // 显示搜索结果提示
    ui->searchResultLabel->setText(QString("找到 %1 条记录").arg(m_currentRecords.size()));
}

// 重置搜索条件
void RecordsViewWidget::onResetClicked()
{
    ui->startDateEdit->setDate(QDate::currentDate().addDays(-30));
    ui->endDateEdit->setDate(QDate::currentDate());
    ui->userComboBox->setCurrentIndex(0);
    ui->itemComboBox->setCurrentIndex(0);
    ui->typeComboBox->setCurrentIndex(0);
    ui->searchResultLabel->clear();
    
    refreshRecords();
}

// 导出记录
void RecordsViewWidget::onExportClicked()
{
    if (m_currentRecords.isEmpty()) {
        QMessageBox::information(this, "提示", "没有记录可以导出！");
        return;
    }
    
    QString fileName = QFileDialog::getSaveFileName(this, 
        "导出操作记录", 
        QString("操作记录_%1.csv").arg(QDate::currentDate().toString("yyyy-MM-dd")),
        "CSV files (*.csv)");
    
    if (!fileName.isEmpty()) {
        exportToCSV(fileName);
    }
}

// 导出为CSV
void RecordsViewWidget::exportToCSV(const QString& fileName)
{
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "错误", "无法创建文件！");
        return;
    }
    
    QTextStream out(&file);
    out.setCodec("GBK");
    
    // 写入CSV头部
    out << QString("ID,时间,操作员,物品名称,操作类型,数量\n");
    
    // 写入数据
    for (const StockRecord& record : m_currentRecords) {
        out << QString("%1,%2,%3,%4,%5,%6\n")
               .arg(record.id)
               .arg(record.timestamp)
               .arg(record.username)
               .arg(record.itemName)
               .arg(record.type)
               .arg(record.quantity);
    }
    
    file.close();
    QMessageBox::information(this, "成功", 
        QString("记录已导出到文件：\n%1\n\n共导出 %2 条记录。").arg(fileName).arg(m_currentRecords.size()));
}

// 查看详情
void RecordsViewWidget::onViewDetailClicked()
{
    if (!hasSelection()) {
        QMessageBox::warning(this, "警告", "请先选择要查看的记录！");
        return;
    }
    
    StockRecord selectedRecord = getSelectedRecord();
    RecordDetailDialog dialog(this);
    dialog.setRecord(selectedRecord);
    dialog.exec();
}

// 表格双击
void RecordsViewWidget::onTableDoubleClicked(int row, int column)
{
    Q_UNUSED(row)
    Q_UNUSED(column)
    
    onViewDetailClicked();
}

// 用户选择变化
void RecordsViewWidget::onUserSelectionChanged()
{
    // 用户选择变化时可以触发自动搜索（可选）
}